package mysql

import (
	"database/sql"
	"fmt"
	"log"
	"time"

	_ "github.com/go-sql-driver/mysql"
	// "time"
)

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
func main() {
	db, _ := sql.Open("mysql", "root:@tcp(localhost:3306)/test?charset=utf8mb4&autocommit=1&parseTime=true")
	defer db.Close()
	err := db.Ping()
	if err != nil {
		log.Println(err)
	}
	fmt.Println("######## 插入数据 #######")
	stmt, err := db.Prepare("INSERT into users SET username=?,password=?,created_at=?,updated_at=?")
	checkErr(err)
	res, err := stmt.Exec("admin2", "admin2", time.Now(), time.Now())
	checkErr(err)

	id, err := res.LastInsertId()
	checkErr(err)

	fmt.Println(id)
	fmt.Println("######## 更新数据 #######")
	// 更新数据
	stmt, err = db.Prepare("update users set username=?,password=? where id=?")
	checkErr(err)

	res, err = stmt.Exec("admin_update", "admin_update", id)
	checkErr(err)

	affect, err := res.RowsAffected()
	checkErr(err)

	fmt.Println(affect)

	fmt.Println("######## 查询数据 #######")
	// 查询数据
	rows, err := db.Query("SELECT id,username,password from users")
	checkErr(err)

	for rows.Next() {
		var id int
		var username string
		var password string
		err = rows.Scan(&id, &username, &password)
		checkErr(err)
		fmt.Println(id)
		fmt.Println(username)
		fmt.Println(password)
	}
	fmt.Println("######## 删除数据 #######")
	// 删除数据
	stmt, err = db.Prepare("delete from users where id =?")
	checkErr(err)

	res, err = stmt.Exec(id)
	checkErr(err)

	affect, err = res.RowsAffected()
	checkErr(err)

	fmt.Println(affect)

}
